package com.wanqing.community.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



/**
 * 解析XML文件
 * @version 
 * Company 
 */
public class SysConfigXmlUtil {

	private static SysConfigXmlUtil instance = null;
	
	private static Logger log = Logger.getLogger(SysConfigXmlUtil.class);
	
	private SysConfigXmlUtil(){}

	public static SysConfigXmlUtil getInstance() {
		if(null==instance){
			instance = new SysConfigXmlUtil();
		}
		return instance;
	}
	
	/**
	 * 解析XML文件
	 * <p>Description:<p>
	 * <p>modifiContent:<p>
	 * @param filename 文件名
	 * @param parentTag 上级标签
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> parseXml(String filename,String parentTag){
		List<Map<String, String>> list = new ArrayList<Map<String,String>>();
		SAXReader builder = new SAXReader();
		try {
			Document doc = builder.read(this.getClass().getClassLoader().getResourceAsStream(filename));
			Element root = doc.getRootElement();
			Element childEle = root.element(parentTag);
			Iterator<Element> childs = childEle.elementIterator();
			Map<String, String> map = null;			
			while(childs.hasNext()){
				map = new LinkedHashMap<String, String>();
				Element child = childs.next();
				String key = child.getName();				
				map.put(key.toLowerCase(), StringTools.objectToString(child.attributeValue("value")));
				list.add(map);
			}
		} catch (Exception e) {			
			log.error(e.toString());
		}		
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, String> parseXmlForMap(String filename,String parentTag){
		Map<String, String> resultMap = new HashMap<String, String>();
		SAXReader builder = new SAXReader();
		try {
			Document doc = builder.read(this.getClass().getClassLoader().getResourceAsStream(filename));
			Element root = doc.getRootElement();
			Element childEle = root.element(parentTag);
			Iterator<Element> childs = childEle.elementIterator();						
			while(childs.hasNext()){				
				Element child = childs.next();
				String key = child.attributeValue("id");
				String value = StringTools.objectToString(child.attributeValue("value"));
				resultMap.put(key, value);
			}
		} catch (Exception e) {			
			log.error(e.toString());
		}	
		return resultMap;
	}
}
